package shiro.shirorealm;

import entity.CroRoleRoot;
import entity.CroUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import service.CroRoleRootService;
import service.CroRoleService;
import service.CroRootService;
import service.CroUserService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuweijie on 17-5-3.
 * 后台登录认证和授权
 */
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private CroUserService croUserService;
    @Autowired
    private CroRoleRootService croRoleRootService;
    @Autowired
    private CroRootService croRootService;
    private CroUser croUser;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("授权");
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        List<String> permissions=new ArrayList<>();
        List<String> roles=new ArrayList<>();
        String username= (String) principalCollection.getPrimaryPrincipal();
//        System.out.println("username"+username);
        croUser=croUserService.findUserByName(username);
        List<CroRoleRoot> croRoleRoots=croRoleRootService.FindRootByRoleId(croUser.getCroRole().getId());
        for(CroRoleRoot croRoleRoot:croRoleRoots){
            String permission=croRootService.FindRootById(croRoleRoot.getCroRoot().getId()).getRoot();
//            System.out.println("权限："+permission);
            permissions.add(permission);
        }
        roles.add(croUser.getCroRole().getRolename());
        info.addRoles(roles);//设置角色
        info.addStringPermissions(permissions);//设置权限
        return info;
    }

    //登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String username= (String) authenticationToken.getPrincipal();
        croUser=croUserService.findUserByName(username);
        if(croUserService==null){
            return null;
        }
        /*
        * 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
        * */
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,croUser.getPassword(),
                ByteSource.Util.bytes(croUser.getSlat()),this.getName());
        return simpleAuthenticationInfo;
    }

    @Override
    public String getName() {
        return getClass().getName();
    }
}
